import { Controller, Get, Post, Body, Put, Delete, Param, Query, ParseIntPipe, UseGuards } from "@nestjs/common";
import { LogsService } from "./logs.service";
import type { CreateLogDto, CreateHttpLogDto, LogQueryOptions } from "./logs.service";
import { LogLevel, Logs, LogType } from "./logs.entity";
import { Can } from "../decorators/casl.decorator";
import { Action } from "../enum/action.enum";
import { JwtGuard } from "../guards/jwt.guard";
import { CaslGuard } from "../guards/casl.guard";

/**
 * 日志控制器 - 处理日志相关的HTTP请求
 *
 * 提供以下功能：
 * - 用户日志查询
 * - 日志统计分析
 * - 系统日志管理
 * - 日志清理维护
 */
@Controller("logs")
@UseGuards(JwtGuard, CaslGuard)
@Can(Action.READ, Logs)
export class LogsController {
  constructor(private readonly logsService: LogsService) {}

  /**
   * 创建日志记录
   * @param createLogDto 日志数据
   */
  @Post()
  @Can(Action.CREATE, Logs)
  async createLog(@Body() createLogDto: CreateLogDto) {
    return this.logsService.createLog(createLogDto);
  }

  /**
   * 创建HTTP请求日志
   * @param httpLogDto HTTP日志数据
   */
  @Post("http")
  @Can(Action.CREATE, Logs)
  async createHttpLog(@Body() httpLogDto: CreateHttpLogDto) {
    return this.logsService.createHttpLog(httpLogDto);
  }

  /**
   * 创建系统日志
   * @param body 系统日志数据
   */
  @Post("system")
  @Can(Action.CREATE, Logs)
  async createSystemLog(
    @Body() body: { message: string; level?: LogLevel; context?: string; meta?: Record<string, unknown> },
  ) {
    return this.logsService.createSystemLog(body.message, body.level || LogLevel.INFO, body.context, body.meta);
  }

  /**
   * 查询用户日志
   * @param userId 用户ID
   * @param query 查询参数
   */
  @Get("user/:userId")
  @Can(Action.READ, Logs)
  async findUserLogs(
    @Param("userId", ParseIntPipe) userId: number,
    @Query()
    query: {
      level?: LogLevel;
      logType?: LogType;
      startDate?: string;
      endDate?: string;
      limit?: string;
      offset?: string;
    },
  ) {
    const options: LogQueryOptions = {
      level: query.level,
      logType: query.logType,
      startDate: query.startDate ? new Date(query.startDate) : undefined,
      endDate: query.endDate ? new Date(query.endDate) : undefined,
      limit: query.limit ? parseInt(query.limit) : undefined,
      offset: query.offset ? parseInt(query.offset) : undefined,
    };

    return this.logsService.findUserLogs(userId, options);
  }

  /**
   * 聚合查询用户日志 - 按结果状态分组
   * @param userId 用户ID
   */
  @Get("user/:userId/group/result")
  async findLogsByGroup(@Param("userId", ParseIntPipe) userId: number) {
    const res = await this.logsService.findLogsByGroup(userId);
    return res.map((item) => ({
      result: item.result,
      count: parseInt(item.count),
    }));
  }

  /**
   * 聚合查询用户日志 - 按日志级别分组
   * @param userId 用户ID
   */
  @Get("user/:userId/group/level")
  async findLogsByLevel(@Param("userId", ParseIntPipe) userId: number) {
    const res = await this.logsService.findLogsByLevel(userId);
    return res.map((item) => ({
      level: item.level,
      count: parseInt(item.count),
    }));
  }

  /**
   * 聚合查询用户日志 - 按日志类型分组
   * @param userId 用户ID
   */
  @Get("user/:userId/group/type")
  async findLogsByType(@Param("userId", ParseIntPipe) userId: number) {
    const res = await this.logsService.findLogsByType(userId);
    return res.map((item) => ({
      logType: item.logType,
      count: parseInt(item.count),
    }));
  }

  /**
   * 获取系统日志统计
   */
  @Get("statistics")
  async getLogStatistics() {
    return this.logsService.getLogStatistics();
  }

  /**
   * 清理过期日志
   * @param body 清理参数
   */
  @Delete("cleanup")
  @Can(Action.DELETE, Logs)
  async cleanupOldLogs(@Body() body: { days?: number }) {
    const days = body.days || 30;
    const deletedCount = await this.logsService.cleanupOldLogs(days);
    return {
      message: `成功清理了 ${deletedCount} 条超过 ${days} 天的日志记录`,
      deletedCount,
      days,
    };
  }

  /**
   * 获取日志级别枚举
   */
  @Get("enums/levels")
  getLogLevels() {
    return Object.values(LogLevel);
  }

  /**
   * 获取日志类型枚举
   */
  @Get("enums/types")
  getLogTypes() {
    return Object.values(LogType);
  }
}
